package com.example.imagetest;

import android.Manifest;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.imagetest.util.LoggingInterceptor;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FileUploadActivity extends AppCompatActivity {

    private static final String TAG = "ImageDownloadAndUpload";
    private static final int PERMISSION_REQUEST_CODE = 1;
    // private static final String FILE_URL = "https://www.baidu.com/img/bd_logo1.png";
    private static final String FILE_URL = "https://www.w3schools.com/html/mov_bbb.mp4";
    private static final String MINIO_UPLOAD_URL = "http://192.168.1.228:8089/product/file/upload";
    private File downloadedFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_upload);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
        } else {
            downloadFile();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                downloadFile();
            } else {
                Log.e(TAG, "Permission denied");
            }
        }
    }

    private void downloadFile() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(FILE_URL).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.e(TAG, "下载图片失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    InputStream inputStream = null;
                    OutputStream outputStream = null;
                    try {
                        // 在设备的外部文件目录中创建一个临时文件，用于存储下载的图片
                        String suffix = FILE_URL.substring(FILE_URL.lastIndexOf("."));
                        Log.e(TAG, "文件后缀名为" + suffix);

                        downloadedFile = File.createTempFile("downloaded_image", suffix, getExternalFilesDir(Environment.DIRECTORY_PICTURES));

                        inputStream = response.body().byteStream();
                        outputStream = new FileOutputStream(downloadedFile);

                        byte[] buffer = new byte[2048];
                        int bytesRead;
                        // 将输入流写入文件输出流
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }

                        // 保存到安卓设备的图库
                        saveImageToGallery(Uri.fromFile(downloadedFile).toString());

                        // 下载成功后，自动上传图片
                        uploadFile(downloadedFile);

                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e(TAG, "图片保存失败: " + e.getMessage());
                    } finally {
                        // 关闭输入流和输出流
                        if (inputStream != null) inputStream.close();
                        if (outputStream != null) outputStream.close();
                    }
                }
            }
        });
    }

    private void saveImageToGallery(String filePath) {
        Log.e(TAG, "图片路径为" + filePath);
        if (filePath.startsWith("file:///"))
            filePath = Uri.parse(filePath).getPath();

        File file = new File(filePath);
        if (!file.exists()) {
            Log.e(TAG, "文件不存在，无法保存到图库: " + filePath);
            return;
        }

        try {
            // 插入媒体库，在 Andriod 应用中的"图库"上显示
            ContentValues values = new ContentValues();
            // ContentValues 用于存储要插入到媒体库中的图片的相关信息
            values.put(MediaStore.Images.Media.DISPLAY_NAME, file.getName());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);

            Uri externalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            Uri uri = getContentResolver().insert(externalUri, values);
            if (uri != null) {
                OutputStream outStream = getContentResolver().openOutputStream(uri);
                FileInputStream inStream = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                outStream.close();
                inStream.close();

                // 更新系统媒体库，通知系统有新文件添加，以便系统可以更新媒体库并在其他应用中显示新添加的图片
                MediaScannerConnection.scanFile(this, new String[]{filePath}, null, (path, uri1) -> {
                    Log.d(TAG, "图片保存并更新到媒体库成功：" + path);
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "保存图片到图库失败: " + e.getMessage());
        }
    }

    private void uploadFile(File file) {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new LoggingInterceptor())
                .build();

        RequestBody fileBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(file, MediaType.parse("image/jpeg")))
                .build();

        Request request = new Request.Builder()
                .url(MINIO_UPLOAD_URL)
                .post(fileBody)
                .build();

        Log.d(TAG, "请求服务的url为:" + MINIO_UPLOAD_URL);
        Log.d(TAG, "上传图片路径: " + file.getAbsolutePath());
        Log.d(TAG, "上传图片大小: " + file.length());

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.e(TAG, "上传图片失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (response.isSuccessful()) {
                        String responseBody = response.body().string();
                        Log.d(TAG, "图片上传成功，响应码: " + response.code());

                        // 使用Gson解析响应体
                        Gson gson = new Gson();
                        JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);

                        if (jsonObject.has("code") && jsonObject.get("code").getAsInt() == 1) {
                            String imageUrl = jsonObject.get("data").getAsString();
                            Log.d(TAG, "图片的访问路径: " + imageUrl);
                        } else {
                            String errorMsg = jsonObject.has("msg") ? jsonObject.get("msg").getAsString() : "未知错误";
                            Log.e(TAG, "上传失败，错误信息: " + errorMsg);
                        }
                    } else {
                        Log.e(TAG, "图片上传失败，响应码: " + response.code());
                    }
                } finally {
                    if (response.body() != null) {
                        response.body().close(); // 关闭响应体
                    }
                }
            }
        });
    }
}